//
//  EMAudioPlayerHelper.m
//  ChatDemo-UI3.0
//
//  Created by XieYajie on 2019/1/29.
//  Copyright © 2019 XieYajie. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>

#import "XGAudioPlayerHelper.h"
#import "amrFileCodec.h"

@interface XGAudioPlayerHelper()<AVAudioPlayerDelegate>

/// 播放路径
@property (nonatomic,copy) NSString *playingPath;
/// 播放器
@property (nonatomic, strong) AVAudioPlayer *player;
/// 完成回调
@property (nonatomic, copy) void (^playerFinished)(NSError *error);

@end

@implementation XGAudioPlayerHelper

#pragma mark - 单例

+ (instancetype)sharedHelper
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

- (void)dealloc
{
    [self stopPlayer];
}

#pragma mark - AVAudioPlayerDelegate

// 播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                       successfully:(BOOL)flag
{
    [self stopPlayer];
}

// 播放发生错误
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player
                                 error:(NSError *)error
{
    if (_playerFinished) {
        NSError *error = [NSError errorWithDomain:@"播放失败!" code:-1 userInfo:nil];
        _playerFinished(error);
    }
    
    [self stopPlayer];
}

#pragma mark - 公开方法

- (void)startPlayerWithPath:(NSString *)aPath completion:(void (^)(NSError *))aCompleton
{
    NSError *error = nil;
    do {
        // 文件不存在
        if (![[NSFileManager defaultManager] fileExistsAtPath:aPath]) {
            error = [NSError errorWithDomain:@"文件路径不存在" code:-1 userInfo:nil];
            break;
        }
        
        if (_player && _player.isPlaying && [_playingPath isEqualToString:aPath]) {
            // 当前音频正处于播放状态
            break;
        } else {
            // 停止当前播放的音频
            [self stopPlayer];
        }
        
//        aPath = [self convertAudioFile:aPath];
//        if ([aPath length] == 0) {
//            error = [NSError errorWithDomain:@"转换音频格式失败" code:-1 userInfo:nil];
//            break;
//        }
                
        NSURL *wavUrl = [[NSURL alloc] initFileURLWithPath:aPath];
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:wavUrl error:&error];
        if (error || !_player) {
            _player = nil;
            error = [NSError errorWithDomain:@"初始化AVAudioPlayer失败" code:-1 userInfo:nil];
            break;
        }
        
        self.playingPath = aPath;
        self.playerFinished = aCompleton;
        _player.delegate = self;
        BOOL success = [_player prepareToPlay];
        if (success) {
            AVAudioSession *audioSession = [AVAudioSession sharedInstance];
            [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
            if (error) {
                break;
            }
        }
        
        success = [_player play];
        if (!success) {
            [self stopPlayer];
            error = [NSError errorWithDomain:@"AVAudioPlayer播放失败" code:-1 userInfo:nil];
        }
        
    } while (0);
    
    
    if (aCompleton) {
        aCompleton(error);
    }
}

- (void)stopPlayer
{
    if(_player) {
        _player.delegate = nil;
        if (_player.isPlaying) {
            [_player stop];
        }
    }
    
    _player = nil;
    _playerFinished = nil;
    _playingPath = nil;
}

#pragma mark - 私有方法

/*
- (int)isMP3File:(NSString *)aFilePath
{
    const char *filePath = [aFilePath cStringUsingEncoding:NSASCIIStringEncoding];
    return isMP3File(filePath);
}

/// 音频格式转换为wav
/// @param aPath 路径名
- (NSString *)convertAudioFile:(NSString *)aPath
{
    // 如果当前音频是mp3
    if ([[aPath pathExtension] isEqualToString:@"mp3"]) {
        return aPath;
    }
        
    // 转换为wav
    NSString *retPath = [[aPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"wav"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:retPath]) {
        return retPath;
    } else if ([self isMP3File:retPath]) {
        return aPath;
    } else {
        EM_DecodeAMRFileToWAVEFile([aPath cStringUsingEncoding:NSASCIIStringEncoding], [retPath cStringUsingEncoding:NSASCIIStringEncoding]);
        if (![fileManager fileExistsAtPath:retPath]) {
            retPath = nil;
        }
        return retPath;
    }
}*/

@end
